﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QqForm
{
    public partial class QqMainList : Form
    {
        private TcpClass tcpClass;
        private Thread thread;
        private List<Message> msgList = new List<Message>();
        public bool isIco = false;
        public QqMainList()
        {
            InitializeComponent();
        }

        public QqMainList(TcpClass tcpClass)
        {
            InitializeComponent();
            lb_msg.Visible = true;
            listView_qqlist.Visible = false;
            this.lb_msg.Text = @"好友列表获取中";
            this.tcpClass = tcpClass;
            thread = new Thread(new ThreadStart(Initial)) { IsBackground = true };
            thread.Start();
            this.timer1.Enabled = true;
        }

        public void Initial()
        {
            tcpClass.messageHelper += new TcpClass.MessageHelper(tcp_messageHelper);
            QqCommand qqHelper = new QqCommand();
            qqHelper.GetQqListSendCommand(tcpClass, "0");
        }

        void tcp_messageHelper(byte[] msg)
        {
            Invoke(new TcpClass.MessageHelper(ShowMessage), new object[] { msg });
        }

        private void ShowMessage(byte[] msg)
        {
            string cmd = Encoding.UTF8.GetString(msg, 0, msg.Length);
            string[] data = cmd.Split('&');
            if (data[1] == "CMD=SIMPLEINFO2")
            {
                new MessageDealGetQqList().ShowMessage(tcpClass, msg);
                InitialQqList();
                lb_msg.Visible = false;
                listView_qqlist.Visible = true;
            }
            if (data[1] == "CMD=QUERY_STAT2")
            {
                GetQqListOnlineShowMessage(msg);
            }
            if (data[1] == "CMD=Server_Msg")//接收消息
            {
                GetQqMsg(msg);
            }
            if (data[1] == "CMD=AddToList")//添加好友
            {
                AddToListShowMessage(msg);
            }
        }

        private void InitialQqList()
        {
            foreach (QqList item in QqListHelper.QqLists)
            {
                int a = 0;
                for (int i = 0; i < this.listView_qqlist.Items.Count; i++)
                {
                    if (item.Uid == listView_qqlist.Items[i].Text)
                    {
                        a = 1;
                        break;
                    }
                }
                if (a == 1)
                {
                    continue;
                }
                ListViewItem lvi = new ListViewItem(item.Uid);
                lvi.SubItems.Add(item.NickName);
                lvi.SubItems.Add(this.GetOnlineState(item.OnlineState.ToString()));
                this.listView_qqlist.Items.Add(lvi);
            }
        }


        #region 获取在线好友列表信息
        /// <summary>
        /// 获取在线好友列表信息
        /// </summary>
        /// <param name="msg"></param>
        public void GetQqListOnlineShowMessage(byte[] msg)
        {
            string cmdQq = Encoding.UTF8.GetString(msg, 0, msg.Length);
            string[] resultArrary = cmdQq.Split('&');
            PostQqServerBackResult backResult = (PostQqServerBackResult)new MessageDealGetQqListOnline().ShowMessage(tcpClass, msg);
            if (backResult.IsSuc)
            {
                QqListOnlineHelper(resultArrary[8], resultArrary[7]);
            }
        }

        #endregion

        #region 获取在线好友列表
        /// <summary>
        /// 获取在线好友列表
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="online"></param>
        private void QqListOnlineHelper(string uid, string online)
        {
            string[] uids = uid.Split('=')[1].Split(',');
            string[] onlines = online.Split('=')[1].Split(',');
            for (int i = 0; i < uids.Length - 1; i++)
            {
                int a = 0;
                foreach (ListViewItem item in this.listView_qqlist.Items)
                {
                    if (uids[i] == item.Text)
                    {
                        item.SubItems[2].Text = this.GetOnlineState(onlines[i]);
                        a = 1;
                        break;
                    }

                }
                if (a == 1)
                {
                    continue;
                }
                ListViewItem lvi = new ListViewItem(uids[i]);
                lvi.SubItems.Add("");
                lvi.SubItems.Add(this.GetOnlineState(onlines[i]));
                this.listView_qqlist.Items.Add(lvi);

            }
        }
        #endregion

        #region 获取消息
        /// <summary>
        /// 获取消息
        /// </summary>
        /// <param name="msg"></param>
        public void GetQqMsg(byte[] msg)
        {
            PostQqServerBackResult backResult = (PostQqServerBackResult)new MessageDealGetQqMsg().ShowMessage(tcpClass, msg);

            if (!backResult.IsSuc)
            {
                return;
            }
            string cmdQq = Encoding.UTF8.GetString(msg, 0, msg.Length);
            string[] resultArrary = cmdQq.Split('&');
            string qqid = (resultArrary[7].Split('='))[1];
            string msgs = ((resultArrary[8].Split('='))[1].Split('\n'))[0].Replace("\r\n", "\r\n");
            string nk = "";
            foreach (ListViewItem item in this.listView_qqlist.Items)
            {
                if (item.Text == qqid)
                {
                    nk = item.SubItems[1].Text;
                    break;
                }
            }
            Message message = new Message(qqid, nk, msgs);
            this.msgList.Add(message);
            this.lb_newMsg.Text = @"您有未读消息(点击查看)......";
            this.pictureBox1.Visible = true;
            string showMsg = msgs;
            ShowMsgNotify showMsgNotify = new ShowMsgNotify(showMsg, nk);
            showMsgNotify.Show();
        }

        #endregion

        #region 获取QQ在线状态
        /// <summary>
        /// 获取QQ在线状态
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetOnlineState(string type)
        {
            string online = "";
            switch (type)
            {
                case "10":
                    online = "在线";
                    break;
                case "20":
                    online = "离线";
                    break;
                case "30":
                    online = "忙碌";
                    break;
                default:
                    online = "离线";
                    break;

            }
            return online;
        }
        #endregion

        #region 列表双击事件
        /// <summary>
        /// 列表双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listView_qqlist_DoubleClick(object sender, EventArgs e)
        {
            SendMsg();
        }
        #endregion

        #region 调用发送消息窗体
        /// <summary>
        /// 调用发送消息窗体
        /// </summary>
        private void SendMsg()
        {
            if (listView_qqlist.SelectedIndices.Count == 0)
            {
                return;
            }
            int index = int.Parse(listView_qqlist.SelectedIndices[0].ToString());
            foreach (ChatFormHelper item in QqUserHelper.ChatFormHelpers)
            {
                if (item.Uid == listView_qqlist.Items[index].Text)
                {
                    item.ChatForm.Show();
                    return;
                }
            }

            ChatForm fm = new ChatForm(tcpClass, listView_qqlist.Items[listView_qqlist.SelectedIndices[0]].SubItems[1].Text, listView_qqlist.Items[listView_qqlist.SelectedIndices[0]].Text);
            ChatFormHelper forming = new ChatFormHelper(listView_qqlist.Items[listView_qqlist.SelectedIndices[0]].Text, fm);
            QqUserHelper.ChatFormHelpers.Add(forming);
            fm.Show();

        }
        #endregion

        #region 退出窗体
        /// <summary>
        /// 退出窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QqMainList_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
        #endregion

        #region 定时器
        private void timer1_Tick(object sender, EventArgs e)
        {
            QqCommand qqHelper = new QqCommand();
            qqHelper.GetQqListIsOnlineCommand(tcpClass, "0");
        }
        #endregion

        #region 处理新消息
        /// <summary>
        /// 处理新消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            if (msgList.Count == 0)
            {
                lb_newMsg.Text = "";
                return;
            }
            ChatForm fm = new ChatForm(tcpClass, msgList[0].Nk, msgList[0].Uid, msgList[0].Msg, msgList[0].Time);
            ChatFormHelper chatForming = new ChatFormHelper(msgList[0].Uid, fm);
            QqUserHelper.ChatFormHelpers.Add(chatForming);

            msgList.RemoveAt(0);

            for (int i = 0; i < msgList.Count; i++)
            {
                if (msgList[i].Uid == msgList[0].Uid)
                {
                    fm.MsgHelper(msgList[i].Msg, msgList[i].Time);
                    msgList.RemoveAt(i);
                }
            }
            fm.Show();
            if (msgList.Count == 0)
            {
                lb_newMsg.Text = "";
            }
        }
        #endregion

        #region 添加好友
        /// <summary>
        /// 添加好友
        /// </summary>
        public void AddToListShowMessage(byte[] msg)
        {
            string cmdQq = Encoding.UTF8.GetString(msg, 0, msg.Length);
            string[] resultArrary = cmdQq.Split('&');
            //AddToUser addToUser = new AddToUser(tcpClass, QqUserHelper.QqNum);
            //addToUser.MessageHelper(resultArrary);
        }

        #endregion

        private void 添加好友ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //AddToUser addToUser = new AddToUser(tcpClass, QqUserHelper.QqNum);
            //addToUser.Show();
        }

        private void notifyIconMsg_Click(object sender, EventArgs e)
        {

        }

        private void QqMainList_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                timer2.Enabled = true;
                this.Hide();//隐藏本窗体
                this.notifyIconMsg.Visible = true;//展示出notifyicon控件
            }
            if (this.WindowState == FormWindowState.Maximized)
            {
                //this.Show();//隐藏本窗体
            }
            this.notifyIconMsg.Icon = new Icon("icon/smst.ico");//将初始化为原来没有闪动的图标
        }

        private void notifyIconMsg_DoubleClick(object sender, EventArgs e)
        {
            timer2.Enabled = false;
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.notifyIconMsg.Visible = false;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            notifyIconMsg.Text = @"您有新消息";
            notifyIconMsg.Icon = new Icon("icon/smsf.ico");
            Thread.Sleep(1000);
            notifyIconMsg.Icon = new Icon("icon/smst.ico");
            Thread.Sleep(1000);
        }
    }
}
